package com.example.lgseckill.service.impl;

import com.example.lgseckill.commom.Constant;
import com.example.lgseckill.commom.utils.RedisUtil;
import com.example.lgseckill.config.LuaScript;
import com.example.lgseckill.domain.SeckillProductPreheatVO;
import com.example.lgseckill.service.ISeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * Author:e
 * Date:2021/8/17 8:59 下午
 **/
@Service
public class SeckillServiceImpl implements ISeckillService {


    private final static Logger logger = LoggerFactory.getLogger(SeckillProductServiceImpl.class);


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LuaScript luaScript;


    /**
     * 校验路径
     */
    @Override
    public boolean checkPath(final Long userId,
                             final Long seckillId,
                             final String uuid) {
        //校验
        String str = (String) redisUtil.get(Constant.SECKILL_PATH_UUID + uuid);
        if (uuid.isEmpty() || str == null) {
            logger.error("uuid无效：{}", uuid);
            return false;
        }
        String[] userIdAndSeckillId = str.split("_");
        if (userIdAndSeckillId.length != 2
                || !seckillId.toString().equals(userIdAndSeckillId[1])
                || !userId.toString().equals(userIdAndSeckillId[0])) {
            return false;
        }
        return true;
    }

    @Override
    public Long getOneSeckillToken(String uuid) {
        return luaScript.tokenCheck(Constant.SECKILL_TOKEM + uuid);
    }

    @Override
    public String createseckillPath(Long userId, Long seckillId) {
        Date now = new Date();
        SeckillProductPreheatVO product = (SeckillProductPreheatVO) redisUtil.get(Constant.SECKILL_PRODUCT_INFO + seckillId);
        //如果redis 不存在或者 当前时间在获取之前
        if (product == null || product.getStartTime().after(now)) {
            return "";
        }

        String uuid = UUID.randomUUID().toString();
        redisUtil.set(Constant.SECKILL_PATH_UUID + uuid, userId + "_" + seckillId, 300);
        logger.info("获取秒杀路径uuid：{}", uuid);
        return uuid;
    }
}
